import { defineStore } from 'pinia'
import { ElMessage } from 'element-plus'

const departmentList = [
  '计算机学院',
  '外国语学院',
  '数学科学学院',
  '物理学院',
  '管理学院',
  '化学学院',
]

const tableData = [
  {
    id: 1,
    courseId: 'C001',
    courseName: '高等数学',
    credit: '4',
    teacher: '王老师',
    department: '数学科学学院',
  },
  {
    id: 2,
    courseId: 'C002',
    courseName: '大学英语',
    credit: '3',
    teacher: '李老师',
    department: '外国语学院',
  },
  {
    id: 3,
    courseId: 'C003',
    courseName: '操作系统',
    credit: '3',
    teacher: '张老师',
    department: '计算机学院',
  },
  {
    id: 4,
    courseId: 'C004',
    courseName: '管理学原理',
    credit: '2',
    teacher: '刘老师',
    department: '管理学院',
  },
  {
    id: 5,
    courseId: 'C005',
    courseName: '大学物理',
    credit: '4',
    teacher: '赵老师',
    department: '物理学院',
  },
]

const useCourseManageStore = defineStore('Course', {
  state: () => ({
    departmentList,
    allData: tableData,
    tableData: tableData,
    queryForm: {
      courseId: '',
      courseName: '',
      department: '',
    },
  }),
  actions: {
    queryData() {
      this.tableData = this.allData.filter((item) => {
        return (
          (!this.queryForm.courseId ||
            item.courseId.includes(this.queryForm.courseId)) &&
          (!this.queryForm.courseName ||
            item.courseName.includes(this.queryForm.courseName)) &&
          (!this.queryForm.department ||
            item.department.includes(this.queryForm.department))
        )
      })
      if (this.tableData.length) {
        ElMessage.success('为你找到以下数据')
      } else {
        ElMessage.error('找不到数据，请检查输入')
      }
    },
    reset() {
      this.tableData = this.allData
      this.queryForm = { courseId: '', courseName: '', department: '' }
    },
    addCourse(course: any) {
      course.id = Date.now()
      this.tableData.unshift(course)
    },
    updateCourse(course: any) {
      const index = this.tableData.findIndex((item) => item.id === course.id)
      if (index !== -1) this.tableData[index] = { ...course }
    },
    remove(id: any) {
      this.tableData = this.tableData.filter((item) => item.id !== id)
      this.allData = this.allData.filter((item) => item.id !== id)
    },
    removeBatch(ids: any) {
      this.tableData = this.tableData.filter((item) => !ids.includes(item.id))
      this.allData = this.allData.filter((item) => !ids.includes(item.id))
    },
  },
})

export default useCourseManageStore
